package com.eso.frame.utils

import org.codehaus.groovy.grails.commons.ConfigurationHolder
import org.apache.commons.lang.StringUtils

/**
 * HTTP/URL工具类
 * Employee: Noah.Rong
 * Version: 0.1,  2012-04-08 14:40
 */
final class HttpUtils {

    /**
     * 获取客户端真实IP地址
     * @param request
     * @return 客户端IP地址
     */
    public static String getIpAddr(request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 获取进入页面时的来源URL
     * @param request http请求对象
     * @return URL字符串
     */
    public static String getSourceURL(request) {
        return request.getHeader("referer");
    }

    /**
     * 获取当前页面的URI
     * @param request http请求对象
     * @return 当前页面的URL地址
     */
    public static String getPageURL(request) {
        String rtnURL = "${ConfigurationHolder.config.grails.serverURL}${request['javax.servlet.forward.request_uri']}";
        //判断
        rtnURL = !StringUtils.isEmpty(request.getQueryString()) ? rtnURL + "?${request.getQueryString()}" : rtnURL.replace("null", "");

        return rtnURL;
    }
}
